package com.oswift.cms.service.impl;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.oswift.cms.dao.MemberDao;
import com.oswift.cms.dao.WebConfigDao;
import com.oswift.cms.dao.reception.ReceptionContentDao;
import com.oswift.cms.entity.DictionaryBean;
import com.oswift.cms.entity.MemberBean;
import com.oswift.cms.entity.MessageBean;
import com.oswift.cms.entity.UserGroupBean;
import com.oswift.cms.entity.WebConfigBean;
import com.oswift.cms.entity.reception.AdZone;
import com.oswift.cms.entity.reception.Announce;
import com.oswift.cms.entity.reception.Article;
import com.oswift.cms.entity.reception.Channel;
import com.oswift.cms.entity.reception.Comment;
import com.oswift.cms.entity.reception.CommonModel;
import com.oswift.cms.entity.reception.DataList;
import com.oswift.cms.entity.reception.Download;
import com.oswift.cms.entity.reception.FontFile;
import com.oswift.cms.entity.reception.FriendSite;
import com.oswift.cms.entity.reception.GuestBook;
import com.oswift.cms.entity.reception.Member;
import com.oswift.cms.entity.reception.Pic;
import com.oswift.cms.entity.reception.QueryWhereBean;
import com.oswift.cms.service.IReceptionService;
import com.oswift.cms.system.cache.CMSCacheFileds;
import com.oswift.cms.system.cache.DictionaryManager;
import com.oswift.cms.utils.Field;
import com.oswift.cms.utils.PageCode;
import com.oswift.cms.utils.ReceptionConstant;
import com.oswift.cms.utils.Field.Appraise;
import com.oswift.cms.utils.Field.CommentAttitude;
import com.oswift.cms.utils.Field.MemberField;
import com.oswift.cms.utils.Field.Upload;
import com.oswift.cms.utils.ReceptionConstant.ContentType;
import com.oswift.utils.cache.ResourceManager;
import com.oswift.utils.common.CipherUtil;
import com.oswift.utils.common.RegexUtils;
import com.oswift.utils.common.StringUtil;
import com.oswift.utils.common.TimeUtil;
import com.oswift.utils.exception.ErrorCode;
import com.oswift.utils.exception.PlatException;
import com.oswift.utils.file.FileUtil;

public class ReceptionServiceImpl implements IReceptionService
{
    /**
     * 日志实例
     */
    private static Logger log = LoggerFactory.getLogger(ReceptionServiceImpl.class);

    /**
     * 字节尺度
     */
    private static int BYTESIZE = 1024;

    /**
     * spring注入对象
     */
    private ReceptionContentDao receptionContentDao;

    /**
     * spring注入对象
     */
    private MemberDao memberDao;

    /**
     * spring对象WebConfigDao注入
     */
    private WebConfigDao webConfigDao;

    /**
     *
     * 查询栏目，查询类型
     * all查询公司下全部栏目，one-level查询全部一级栏目，fixed-all查询指定栏目及其所有父栏目和所有子栏目，fixed-one查询指定栏目
     *
     * @author zhuou
     * @param companyId
     *            公司Id
     * @channelId 栏目Id
     * @contentType 查询类型
     * @throws PlatException
     *             公共异常
     */
    public Object getChannel(int companyId, int channelId, String contentType)
        throws PlatException
    {
        if (ContentType.CHANNEL_ONE_LEVEL.equals(contentType))
        {
            List<Channel> list = receptionContentDao.getChannel(companyId,
                    channelId, ContentType.CHANNEL_ONE_LEVEL);
            return list;
        }
        else if (ContentType.CHANNEL_FIXED_ALL.equals(contentType))
        {
            Channel channel = null;

            // 查询出所有栏目
            List<Channel> list = receptionContentDao.getChannel(companyId, -1,
                    ContentType.CHANNEL_ALL);

            // 获取当前栏目
            for (Channel item : list)
            {
                if (item.getChannelId() == channelId)
                {
                    channel = item;
                }
            }
            if (null == channel)
            {
                return null;
            }

            // 获取此栏目的所有子栏目
            sortChannel(list, channel);

            // 获取所有父栏目
            getParentChannel(list, channel);
            return channel;
        }
        else if (ContentType.CHANNEL_FIXED_ONE.equals(contentType))
        {
            List<Channel> list = receptionContentDao.getChannel(companyId,
                    channelId, ContentType.CHANNEL_FIXED_ONE);
            if (null == list || list.isEmpty())
            {
                return null;
            }
            return list.get(0);
        }
        // 获取所有栏目
        else
        {
            List<Channel> list = receptionContentDao.getChannel(companyId,
                    channelId, ContentType.CHANNEL_ALL);
            // 如果为null值返回一个空list对象
            if (null == list || list.isEmpty())
            {
                return new ArrayList<Channel>();
            }
            // 获取一级栏目
            List<Channel> parentList = new ArrayList<Channel>();
            for (Channel item : list)
            {
                if (item.getParentId() == Field.PARENT_ID)
                {
                    parentList.add(item);
                }
            }
            // 处理list，将栏目的子栏目数据按顺序填充到Channel
            for (Channel item : parentList)
            {
                sortChannel(list, item);
            }
            return parentList;
        }
    }

    /**
     *
     * 获取此栏目下的子栏目，并将栏目信息按次序放入到chennel
     *
     * @author zhuou
     * @param list
     *            要处理的列表
     * @param chennel
     *            获取此栏目下的子栏目，并将栏目信息按次序放入到chennel
     */
    private void sortChannel(List<Channel> list, Channel chennel)
    {
        List<Channel> childList = new ArrayList<Channel>();
        for (Channel item : list)
        {
            if (item.getParentId() == chennel.getChannelId())
            {
                childList.add(item);

                if (item.isChild())
                {
                    sortChannel(list, chennel);
                }
            }
        }
        if (null != childList && !childList.isEmpty())
        {
            // 排序
            Collections.sort(childList, new Comparator<Channel>()
            {
                @Override
                public int compare(Channel item1, Channel item2)
                {
                    return item1.getSort() > item2.getSort() ? 1 : 0;
                }
            });
        }
        chennel.setChildList(childList);
    }

    /**
     *
     * 将一个栏目的所有父栏目检索到放到list中
     *
     * @author zhuou
     * @param list
     *            栏目列表
     * @param chennel
     *            目标栏目
     */
    private void getParentChannel(List<Channel> list, Channel chennel)
    {
        if (chennel.getParentId() != Field.PARENT_ID)
        {
            for (Channel item : list)
            {
                if (item.getChannelId() == chennel.getParentId())
                {
                    chennel.setParent(item);
                    getParentChannel(list, item);
                    break;
                }
            }
        }
    }

    /**
     *
     * 根据别名查询出栏目信息
     *
     * @author zhuou
     * @param companyId
     *            公司Id
     * @param nickName
     *            别名
     * @return Channel
     */
    public Channel getChannelByNickName(int companyId, String nickName)
        throws PlatException
    {
        return receptionContentDao.getChannelByNickName(companyId, nickName);
    }

    /**
     *
     * 根据栏目id获取栏目信息
     *
     * @author zhuou
     * @param channelId
     *            栏目id
     * @return Channel
     * @throws PlatException
     *             公共异常
     */
    public Channel getChannelById(int channelId) throws PlatException
    {
        return receptionContentDao.getChannelById(channelId);
    }

    /**
     *
     * 根据内容类型获取查询条件
     *
     * @author zhuou
     * @param type
     * @return QueryWhereBean
     */
    private QueryWhereBean queryContentWhere(String type)
    {
        QueryWhereBean bean = new QueryWhereBean();
        if (ContentType.NEW.equalsIgnoreCase(type))
        {
            bean.setOrderColumn("PassedTime");
            bean.setOrderType(true);
        }
        else if (ContentType.HOT.equalsIgnoreCase(type))
        {
            bean.setOrderColumn("Hits DESC,PassedTime");
            bean.setOrderType(true);
        }
        else if (ContentType.MONTHHOT.equalsIgnoreCase(type))
        {
            bean.setOrderColumn("MonthHits DESC,PassedTime");
            bean.setOrderType(true);
        }
        else if (ContentType.WEEKHOT.equalsIgnoreCase(type))
        {
            bean.setOrderColumn("WeekHits DESC,PassedTime");
            bean.setOrderType(true);
        }
        else if (ContentType.DAYHOT.equalsIgnoreCase(type))
        {
            bean.setOrderColumn("DayHits DESC,PassedTime");
            bean.setOrderType(true);
        }
        else if (ContentType.IMGTXT.equalsIgnoreCase(type))
        {
            bean.setStrWhere(" AND ContentImgNum>0 ");
            bean.setOrderColumn("PassedTime");
            bean.setOrderType(true);
        }
        else if (ContentType.FOCUS.equalsIgnoreCase(type))
        {
            bean.setStrWhere(" AND FocusImgNum>0 ");
            bean.setOrderColumn("PassedTime");
            bean.setOrderType(true);
        }
        else if (ContentType.BIGNEWS.equalsIgnoreCase(type))
        {
            bean.setStrWhere(" AND BigNewsImgNum>0 ");
            bean.setOrderColumn("PassedTime");
            bean.setOrderType(true);
        }
        else if (ContentType.MARQUEE.equalsIgnoreCase(type))
        {
            bean.setStrWhere(" AND MarqueeImgNum>0 ");
            bean.setOrderColumn("PassedTime");
            bean.setOrderType(true);
        }
        else if (ContentType.RECOMMEND.equalsIgnoreCase(type))
        {
            bean.setOrderColumn("EliteLevel DESC,PassedTime");
            bean.setOrderType(true);
        }
        else if (ContentType.PRIORITY.equalsIgnoreCase(type))
        {
            bean.setOrderColumn("Priority DESC,PassedTime");
            bean.setOrderType(true);
        }
        else if (ContentType.MOSTCOMMENT.equalsIgnoreCase(type))
        {
            bean.setOrderColumn("CommentCount DESC,PassedTime");
            bean.setOrderType(true);
        }
        else if (ContentType.DEFAULTIMG.equalsIgnoreCase(type))
        {
            bean
                    .setStrWhere(" AND DefaultPicUrl IS NOT NULL AND DefaultPicUrl<>'' ");
            bean.setOrderColumn("PassedTime");
            bean.setOrderType(true);
        }
        // 用户自定义搜索条件并且根据那个字段排序，如果没有orderBy则默认PassedTime
        // 降序，如：defined:PicGalleryAuthor LIKE '%朱欧'orderby:Priority asc
        else if (type.indexOf(ContentType.USER_DEFINED) != -1)
        {
            String whereStr = type.substring(ContentType.USER_DEFINED.length());
            if (!StringUtil.isBlank(whereStr))
            {
                // 是否有自定义排序
                if (whereStr.toLowerCase().indexOf(
                        ContentType.USER_DEFINED_ORDERBY) != -1)
                {
                    // 获取where条件
                    String whereStr1 = whereStr.substring(0, whereStr
                            .indexOf(ContentType.USER_DEFINED_ORDERBY));
                    if (!StringUtil.isBlank(whereStr1))
                    {
                        bean.setStrWhere(" AND " + whereStr1);
                    }

                    // 获取排序条件
                    String orderBy = whereStr.substring(whereStr1.length()
                            + ContentType.USER_DEFINED_ORDERBY.length());
                    if (!StringUtil.isBlank(orderBy))
                    {
                        if (orderBy.lastIndexOf(' ') != -1)
                        {
                            String column = orderBy.substring(0, orderBy
                                    .lastIndexOf(' '));
                            if (!StringUtil.isBlank(column))
                            {
                                // 排序列
                                bean.setOrderColumn(column.trim());

                                // 排序条件
                                String sort = orderBy.substring(orderBy
                                        .lastIndexOf(' '));
                                if (!StringUtil.isBlank(sort))
                                {
                                    if (sort.trim().equalsIgnoreCase(
                                            ReceptionConstant.OrderBy.ASC))
                                    {
                                        bean.setOrderType(false);
                                    }
                                    else if (sort.trim().equalsIgnoreCase(
                                            ReceptionConstant.OrderBy.DESC))
                                    {
                                        bean.setOrderType(true);
                                    }
                                    else
                                    {
                                        bean.setOrderType(false);
                                    }
                                }
                                else
                                {
                                    bean.setOrderType(false);
                                }
                            }
                        }
                        else
                        {
                            bean.setOrderColumn(orderBy.trim());
                            bean.setOrderType(false);
                        }
                    }
                }
                else
                {
                    bean.setStrWhere(" AND " + whereStr);
                }
            }
            else
            {
                bean.setOrderColumn("PassedTime");
                bean.setOrderType(true);
            }
        }
        else
        {
            bean.setOrderColumn("PassedTime");
            bean.setOrderType(true);
        }
        return bean;
    }

    /**
     *
     * 评论查询条件
     *
     * @author zhuou
     * @param type
     *            类型
     * @return QueryWhereBean
     */
    private QueryWhereBean queryCommentWhere(String type)
    {
        QueryWhereBean bean = new QueryWhereBean();
        if (ContentType.NEW.equalsIgnoreCase(type))
        {
            bean.setOrderColumn("CreateTime");
            bean.setOrderType(true);
        }
        else if (ContentType.RECOMMEND.equalsIgnoreCase(type))
        {
            bean.setStrWhere(" AND IsElite>0 ");
            bean.setOrderColumn("CreateTime");
            bean.setOrderType(true);
        }
        else
        {
            bean.setOrderColumn("CreateTime");
            bean.setOrderType(true);
        }
        return bean;
    }

    /**
     *
     * 根据内容id获取栏目信息
     *
     * @author zhuou
     * @param commonModelId
     *            内容Id
     * @return Channel
     * @throws PlatException
     *             公共异常
     */
    public Channel getChannelByCommonModelId(long commonModelId)
        throws PlatException
    {
        return receptionContentDao.getChannelByCommonModelId(commonModelId);
    }

    /**
     *
     * 增加广告点击数
     *
     * @author zhuou
     * @param adId
     *            广告id
     * @return boolean
     * @throws PlatException
     *             公共异常
     */
    public boolean addAdClicks(int adId)
    {
        boolean isSuccess = false;
        try
        {
            isSuccess = receptionContentDao.addAdClicks(adId) > 0 ? true
                    : false;
        }
        catch (PlatException e)
        {
            // 异常信息已经记录日志，此处异常抛弃
        }
        return isSuccess;
    }

    /**
     *
     * 新增评论
     *
     * @author zhuou
     * @param commentbean
     *            参数
     * @return int
     * @throws PlatException
     *             公共异常
     */
    public boolean addComment(Comment commentbean, boolean isPrivate)
        throws PlatException
    {
        // 当评论标题为空，将内容的标题赋值给CommentTitle
        if (StringUtil.isBlank(commentbean.getCommentTitle()))
        {
            CommonModel commonModel = receptionContentDao
                    .getCommonModelById(commentbean.getCommonModelId());
            if (null != commonModel)
            {
                commentbean.setCommentTitle(commonModel.getTitle());
            }
        }

        boolean isSuccess = receptionContentDao.addComment(commentbean,
                isPrivate) > 0 ? true : false;

        // 更新评论总数
        if (isSuccess)
        {
            receptionContentDao.updateCommentCount(commentbean
                    .getCommonModelId());
        }

        return isSuccess;
    }

    /**
     *
     * 新增对评论的反对 赞成 中立
     *
     * @author zhuou
     * @param commentId
     *            评论Id
     * @param type
     *            是反对 赞成 中立
     * @return boolean
     * @throws PlatException
     *             公共异常
     */
    public boolean commentAttitude(long commentId, String type)
        throws PlatException
    {
        boolean isSuccess = true;
        if (CommentAttitude.AGREE.equals(type))
        {
            isSuccess = receptionContentDao.commentAgree(commentId) > 0 ? true
                    : false;
        }
        else if (CommentAttitude.NEUTRAL.equals(type))
        {
            isSuccess = receptionContentDao.commentNeutral(commentId) > 0 ? true
                    : false;
        }
        else if (CommentAttitude.OPPOSE.equals(type))
        {
            isSuccess = receptionContentDao.commentOppose(commentId) > 0 ? true
                    : false;
        }
        else
        {
            log.error("Parameter error, parameter type does not exist.type="
                    + type);
            isSuccess = false;
        }

        return isSuccess;
    }

    /**
     *
     * 文章点赞或者踩
     *
     * @author zhuou
     * @param articleId
     *            文章Id
     * @param type
     *            类型
     * @return boolean
     * @throws PlatException
     *             公共异常
     */
    public boolean clickAppraise(long articleId, String type)
        throws PlatException
    {
        boolean isSuccess = true;
        if (Appraise.PRAISE.equals(type))
        {
            isSuccess = receptionContentDao.addPraise(articleId) > 0 ? true
                    : false;
        }
        else if (Appraise.TREAD.equals(type))
        {
            isSuccess = receptionContentDao.addTread(articleId) > 0 ? true
                    : false;
        }
        else
        {
            log.error("Parameter error, parameter type does not exist.type="
                    + type);
            isSuccess = false;
        }
        return isSuccess;
    }

    /**
     *
     * 新增留言
     *
     * @author zhuou
     * @param bean
     *            留言
     * @companyId 公司Id
     * @status 状态
     * @return boolean
     * @throws PlatException
     *             公共异常
     */
    public boolean addGuestbook(GuestBook bean, int companyId, int status)
        throws PlatException
    {
        // 如果为0，则赋默认值
        if (bean.getChannelId() <= 0)
        {
            DictionaryBean dBean = DictionaryManager
                    .getValue(CMSCacheFileds.BusinessField.DEFAULT_GUESTBOOK_KEY);
            Channel defaultChannel = receptionContentDao.getDefaultChannel(
                    companyId, dBean.getFieldValue());
            bean.setChannelId(defaultChannel.getChannelId());
        }
        return receptionContentDao.addGuestbook(bean, companyId, status);
    }

    /**
     *
     * 新增文章
     *
     * @author zhuou
     * @param bean
     *            文章实体bean
     * @param companyId
     *            公司Id
     * @param status
     *            状态
     * @return boolean
     * @throws PlatException
     *             公共异常
     */
    public boolean addArticle(Article bean, int companyId, int status)
        throws PlatException
    {
        // 如果为0，则赋默认值
        if (bean.getChannelId() <= 0)
        {
            DictionaryBean dBean = DictionaryManager
                    .getValue(CMSCacheFileds.BusinessField.DEFAULT_ARTICLE_KEY);
            Channel defaultChannel = receptionContentDao.getDefaultChannel(
                    companyId, dBean.getFieldValue());
            bean.setChannelId(defaultChannel.getChannelId());
        }

        return receptionContentDao.addArticle(bean, companyId, status);
    }

    /**
     *
     *
     * 获取内容列表数据
     *
     * @author zhuou
     * @param companyId
     *            表示公司Id，可以从后台获取
     * @param channelId
     *            栏目Id 如果为-1则获取所有栏目文章列表
     * @param contentType
     *            内容类型
     * @param pageNum
     *            每页记录数
     * @param nowPage
     *            当为-1时表示不分页，大于0表示分页的第几页
     * @param tableName
     *            表名
     * @return Object
     */
    public DataList contentList(int companyId, int channelId,
            String contentType, int pageNum, int nowPage, String tableName)
        throws PlatException
    {
        // 提取内容数据
        QueryWhereBean bean = queryContentWhere(contentType);
        DataList data = null;
        if (nowPage > 0)
        {
            data = receptionContentDao.getContentPage(pageNum, bean
                    .getStrWhere(), bean.getOrderColumn(), bean.isOrderType(),
                    channelId, companyId, nowPage, tableName);
        }
        else
        {
            data = receptionContentDao.getContentListNoPage(pageNum, bean
                    .getStrWhere(), bean.getOrderColumn(), bean.isOrderType(),
                    channelId, companyId, tableName);
        }
        return data;
    }

    /**
     *
     * 根据广告位获取广告
     *
     * @author zhuou
     * @param zoneId
     *            广告位
     * @param topNum
     *            取几条广告
     * @return AdZone
     */
    public AdZone getAdvertisement(int zoneId, int companyId, int topNum)
    {
        return receptionContentDao.getAdvertisement(zoneId, companyId, topNum);
    }

    /**
     *
     * 根据广告位编码查询广告
     *
     * @author zhuou
     * @param zoneCode
     *            广告位编码
     * @param companyId
     *            公司Id
     * @param topNum
     *            取几条广告
     * @return AdZone
     */
    public AdZone getAdvertisement(String zoneCode, int companyId, int topNum)
    {
        AdZone adZone = receptionContentDao.getAdZoneByZoneCode(zoneCode,
                companyId);
        if (null == adZone)
        {
            adZone = new AdZone();
            return adZone;
        }
        return receptionContentDao.getAdvertisement(adZone.getZoneId(),
                companyId, topNum);
    }

    /**
     *
     * 获取评论列表信息
     *
     * @author zhuou
     * @param companyId
     *            单位Id
     * @param commonModelId
     *            内容id 如果为-1则表示从所有评论中获取，否则获取内容ID的评论信息
     * @param contentType
     *            内容类型
     * @param pageNum
     *            获取记录数，如果有分页，则表示每页记录数
     * @param nowPage
     *            当为-1时表示不分页，大于-1表示分页的第几页
     *
     * @return Object
     * @throws PlatException
     *             公共异常
     */
    public Object getCommentList(int companyId, long commonModelId,
            String contentType, int pageNum, int nowPage) throws PlatException
    {
        // 提取查询条件
        QueryWhereBean bean = queryCommentWhere(contentType);
        if (nowPage > 0)
        {
            return receptionContentDao.getCommentPage(pageNum, commonModelId,
                    bean.getStrWhere(), bean.getOrderColumn(), bean
                            .isOrderType(), companyId, nowPage);
        }
        else
        {
            return receptionContentDao.getCommentNoPage(pageNum, commonModelId,
                    bean.getStrWhere(), bean.getOrderColumn(), bean
                            .isOrderType(), companyId);
        }
    }

    /**
     *
     * 获取文章详情
     *
     * @author zhuou
     * @param commonId
     *            内容Id
     * @param companyId
     *            前台页面传过来的公司Id，为了防止多站点情况下通过修改url的id获取到其他网站的内容
     * @param isRelation
     *            是否要获取这篇内容的上一篇，下一篇内容
     * @param relationFlag
     *            当isRelation为true，此字段起作用。 当relationFlag=1时获取的是本栏目下的相关上一条下一条记录，
     *            当relationFlag=2时获取文章板块下上一条下一条记录，
     *            当relationFlag=3时获取本栏目及其子栏目下的文章上一条下一条记录
     * @return Article
     * @throws PlatException
     *             公共异常
     */
    public Article getArticleDetail(long commonId, int companyId,
            boolean isRelation, int relationFlag) throws PlatException
    {
        return receptionContentDao.getArticleDetail(commonId, companyId,
                isRelation, relationFlag);
    }

    /**
     *
     * 获取公告详情
     *
     * @author zhuou
     * @param commonId
     *            内容Id
     * @param isRelation
     *            是否要获取这篇公告的上一篇，下一篇内容
     * @return Announce
     * @throws PlatException
     *             公共异常
     */
    public Announce getAnnounceDetail(long commonId, boolean isRelation)
        throws PlatException
    {
        return receptionContentDao.getAnnounceDetail(commonId, isRelation);
    }

    /**
     *
     * 获取下载详情
     *
     * @author zhuou
     * @param commonId
     *            内容Id
     * @param isRelation
     *            是否要获取这篇下载的上一篇，下一篇内容
     * @return Download
     * @throws PlatException
     *             公共异常
     */
    public Download getDownloadDetail(long commonId, boolean isRelation)
        throws PlatException
    {
        return receptionContentDao.getDownloadDetail(commonId, isRelation);
    }

    /**
     *
     * 获取图片详情
     *
     * @author zhuou
     * @param commonId
     *            内容Id
     * @param isRelation
     *            是否要获取这篇图片的上一篇，下一篇内容
     * @return Pic
     * @throws PlatException
     *             公共异常
     */
    public Pic getPicDetail(long commonId, boolean isRelation)
        throws PlatException
    {
        return receptionContentDao.getPicDetail(commonId, isRelation);
    }

    /**
     *
     * 获取留言详情
     *
     * @author zhuou
     * @param commonId
     *            内容Id
     * @param isRelation
     *            是否要获取这篇留言的上一篇，下一篇内容
     * @return GuestBook
     * @throws PlatException
     *             公共异常
     */
    public GuestBook getGuestBookDetail(long commonId, boolean isRelation)
        throws PlatException
    {
        return receptionContentDao.getGuestBookDetail(commonId, isRelation);
    }

    /**
     *
     * 获取友情链接详情
     *
     * @author zhuou
     * @param commonId
     *            内容Id
     * @param isRelation
     *            是否要获取这篇友情链接的上一篇，下一篇内容
     * @return FriendSite
     * @throws PlatException
     *             公共异常
     */
    public FriendSite getFriendSiteDetail(long commonId, boolean isRelation)
        throws PlatException
    {
        return receptionContentDao.getFriendSiteDetail(commonId, isRelation);
    }

    /**
     *
     * 会员注册
     *
     * @author zhuou
     * @param memberBean
     *            会员实体类
     * @return boolean
     * @throws PlatException
     *             公共异常
     */
    public MessageBean memberRegister(MemberBean memberBean, int companyId)
        throws PlatException
    {
        MessageBean messBean = new MessageBean();

        // 用户名是否存在
        boolean isExist = memberDao.isExistByUserName(memberBean.getUserName(),
                companyId);
        if (isExist)
        {
            messBean.setCode(PageCode.EXISTUSERNAME);
            messBean.setContent(ResourceManager
                    .getValue(PageCode.EXISTUSERNAME));
            return messBean;
        }

        // 如果email不为空，则判断此邮箱是否存在，不能用重复邮箱注册
        if (!StringUtil.isBlank(memberBean.getEmail()))
        {
            isExist = memberDao
                    .isExistByEmail(memberBean.getEmail(), companyId);
            if (isExist)
            {
                messBean.setCode(PageCode.MEMBER_EMAIL_EXIST);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.MEMBER_EMAIL_EXIST));
                return messBean;
            }
        }

        // 如果没有GroupId，则获取默认的用户组信息
        if (memberBean.getGroupId() <= 0)
        {
            UserGroupBean userGroupBean = memberDao
                    .getDefaultUserGroup(companyId);
            if (null == userGroupBean)
            {
                throw new PlatException(PageCode.MEMBERGROUP_ISNOT_EXIST);
            }
            memberBean.setGroupId(userGroupBean.getGroupId());
        }

        // 对密码进行加密
        memberBean.setUserPassword(CipherUtil.generatePassword(memberBean
                .getUserPassword()));
        // 新增主表
        int rows = memberDao.add(memberBean);
        if (rows <= 0)
        {
            messBean.setCode(ErrorCode.COMMON_DB_ERROR);
            return messBean;
        }

        // 新增扩张表
        rows = memberDao.addContacter(memberBean);
        if (rows <= 0)
        {
            throw new PlatException(ErrorCode.COMMON_DB_ERROR);
        }
        messBean.setCode(PageCode.COMMON_SUCCESS);
        return messBean;
    }

    /**
     *
     * 会员登录
     *
     * @author zhuou
     * @param companyId
     *            公司Id
     * @param userName
     *            用户名
     * @param password
     *            密码
     * @param loginIp
     *            登录Ip
     * @return MessageBean
     * @throws PlatException
     *             公共异常
     */
    public MessageBean memberLogin(int companyId, String userName,
            String password, String loginIp) throws PlatException
    {
        // 设置返回信息
        MessageBean messBean = new MessageBean();

        MemberBean memberBean = null;
        // userName如果是Email，则用Email登录
        boolean isEmail = RegexUtils.isEmail(userName);
        if (isEmail)
        {
            memberBean = memberDao.getUserByEmail(userName, companyId);
        }
        else
        {
            memberBean = memberDao.getUserByUserName(userName, companyId);
        }

        // 如果为null，则证明没有此用户不存在
        if (null == memberBean)
        {
            messBean.setCode(PageCode.MEMBERLOGIN_USERNAMEERROR);
            String mess = ResourceManager
                    .getValue(PageCode.MEMBERLOGIN_USERNAMEERROR);
            if (isEmail)
            {
                messBean.setContent(mess
                        .replace("{0}", MemberField.LOGIN_EMAIL));
            }
            else
            {
                messBean.setContent(mess.replace("{0}",
                        MemberField.LOGIN_USERNAME));
            }
            return messBean;
        }

        // 判断密码是否正确
        String inPassword = CipherUtil.generatePassword(password);
        if (!inPassword.equals(memberBean.getUserPassword()))
        {
            int failedPasswordAttemptCount = memberBean
                    .getFailedPasswordAttemptCount() + 1;
            int loginTimes = memberBean.getLoginTimes() + 1;

            // 更新登录信息
            memberDao.updateMemberWhenLogin(loginTimes, new Date(), loginIp,
                    failedPasswordAttemptCount, memberBean.getUserId());

            messBean.setCode(PageCode.MEMBERLOGIN_PASSWORDERROR);
            messBean.setContent(ResourceManager
                    .getValue(PageCode.MEMBERLOGIN_PASSWORDERROR));
            messBean.setObjContent(failedPasswordAttemptCount);
            return messBean;
        }

        // 判断账户是否被锁定
        if (ReceptionConstant.MemberConstant.Status.LOCK == memberBean
                .getStatus())
        {
            messBean.setCode(PageCode.MEMBER_LOCKED);
            messBean.setContent(ResourceManager
                    .getValue(PageCode.MEMBER_LOCKED));
            return messBean;
        }

        Member member = new Member();
        member.setUserId(memberBean.getUserId());
        member.setUserName(memberBean.getUserName());
        member.setUserFace(memberBean.getUserFace());
        member.setUserExp(memberBean.getUserExp());
        member.setGroupName(memberBean.getGroupName());
        member.setGroupId(memberBean.getGroupId());
        member.setFaceWidth(memberBean.getFaceWidth());
        member.setFaceHeight(memberBean.getFaceWidth());
        member.setConsumeExp(memberBean.getConsumeExp());

        int loginTimes = memberBean.getLoginTimes() + 1;
        // 更新登录信息
        memberDao.updateMemberWhenLogin(loginTimes, new Date(), loginIp, 0,
                memberBean.getUserId());

        messBean.setCode(PageCode.COMMON_SUCCESS);
        messBean.setContent(ResourceManager
                .getValue(PageCode.MEMBERLOGIN_SUCCESS));
        messBean.setObjContent(member);

        return messBean;
    }

    /**
     *
     * 上传图片，并保存到磁盘上
     *
     * @author zhuou
     * @param request
     *            HttpServletRequest
     * @param companyId
     *            单位ID
     * @return UploadBean
     */
    public MessageBean uploadImg(HttpServletRequest request, int companyId)
        throws PlatException
    {
        // 设置返回信息
        MessageBean messBean = new MessageBean();
        messBean.setCode(PageCode.COMMON_ERROR);
        try
        {
            // 从Request获取图片数据
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            MultipartFile imgFile = multipartRequest.getFile("imgFile");

            // 保存图片
            if (null == imgFile.getOriginalFilename()
                    || "".equals(imgFile.getOriginalFilename()))
            {
                messBean.setCode(PageCode.UPLOAD_IMG_ISEMPTY);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.UPLOAD_IMG_ISEMPTY));
                return messBean;
            }

            // 获取文件名称
            String fileName = imgFile.getOriginalFilename();

            // 获取上传文件类型的扩展名,先得到.的位置，再截取从.的下一个位置到文件的最后，最后得到扩展名
            String ext = fileName.substring(fileName.lastIndexOf(".") + 1,
                    fileName.length());

            // 对扩展名进行小写转换
            ext = ext.toLowerCase();

            // 判断上传的类型是否符合容许上传图片类型
            String imgExt = Upload.DEFAULT_UPLOADIMG_TYPE;

            // 查询出配置
            WebConfigBean webBean = webConfigDao.selectOne(companyId);
            if (null != webBean
                    && !StringUtil.isEmpty(webBean.getUpLoadImgType()))
            {
                imgExt = webBean.getUpLoadImgType();
            }

            String[] imgExts = imgExt.split(Upload.FILE_SEPARATOR);
            List<String> imgExtList = new ArrayList<String>();
            for (String s : imgExts)
            {
                imgExtList.add(s.toLowerCase());
            }

            // 判断是否符合要求
            if (!imgExtList.contains(ext))
            {
                messBean.setCode(PageCode.IMG_TYPE_ERROR);
                messBean.setContent(StringUtil.replace(ResourceManager
                        .getValue(PageCode.IMG_TYPE_ERROR), imgExt));
                return messBean;
            }

            int fileSize = (int) imgFile.getSize() / BYTESIZE;
            // 判读图片大小是否超过最大的限制大小
            String maxSize = request.getParameter("maxSize");
            if (RegexUtils.isNumber(maxSize))
            {
                int iMaxSize = Integer.valueOf(maxSize);
                if (fileSize > (iMaxSize * BYTESIZE))
                {
                    messBean.setCode(PageCode.UPLOADIMG_MAXSIZE_TOOBIG);
                    messBean.setContent(StringUtil.replace(ResourceManager
                            .getValue(PageCode.UPLOADIMG_MAXSIZE_TOOBIG),
                            maxSize));
                    return messBean;
                }
            }

            // 获取当前时间，文件命名需要
            Date date = new Date();

            // 文件保存路径
            StringBuilder path = new StringBuilder();
            String realPath = request.getSession().getServletContext()
                    .getRealPath("");
            path.append(realPath);

            // 相对路径
            StringBuilder contextPath = new StringBuilder();
            contextPath.append(request.getContextPath());
            contextPath.append(Upload.URL_SEPARATOR);

            // 文件路径分隔符
            path.append(FileUtil.FILE_SEPARATOR);
            path.append(Upload.UPLOAD_ROOT_FILENAME);
            contextPath.append(Upload.UPLOAD_ROOT_FILENAME);

            // 文件路径分隔符
            contextPath.append(Upload.URL_SEPARATOR);
            path.append(FileUtil.FILE_SEPARATOR);

            // 单位Id，作为存储每个用户文件的路径
            contextPath.append(companyId);
            path.append(companyId);

            // 文件路径分隔符
            contextPath.append(Upload.URL_SEPARATOR);
            path.append(FileUtil.FILE_SEPARATOR);

            // 存储图片的文件夹
            contextPath.append(Upload.UPLOAD_IMG_FILENAME);
            path.append(Upload.UPLOAD_IMG_FILENAME);

            // 文件路径分隔符
            contextPath.append(Upload.URL_SEPARATOR);
            path.append(FileUtil.FILE_SEPARATOR);

            // 按月存储图片文件
            String folder = TimeUtil.dateToString(date,
                    TimeUtil.COMPACT_DATE_FORMAT);
            contextPath.append(folder);
            path.append(folder);

            // 新建文件夹，如果父文件夹不存在，遍历新建
            boolean isSuccess = FileUtil.createDirectory(path.toString());

            // 失败直接返回
            if (!isSuccess)
            {
                messBean.setCode(PageCode.CREATE_FOLDER_FAIL);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.CREATE_FOLDER_FAIL));
                return messBean;
            }

            // 文件路径分隔符
            contextPath.append(Upload.URL_SEPARATOR);
            path.append(FileUtil.FILE_SEPARATOR);

            // 定义图片新名称
            String newName = TimeUtil.dateToString(date,
                    TimeUtil.COMPACT_DATE_TIME_MS_FORMAT);
            path.append(newName);
            path.append('.');
            path.append(ext);
            contextPath.append(newName);
            contextPath.append('.');
            contextPath.append(ext);

            // 保存
            File img = new File(path.toString());
            imgFile.transferTo(img);

            // 查看是否有重复的图片存在
            List<FontFile> imgFiles = receptionContentDao.getFilesbySize(
                    companyId, fileSize);
            List<FontFile> existImgs = new ArrayList<FontFile>();
            if (null != imgFiles && !imgFiles.isEmpty())
            {
                String md5 = FileUtil.getFileMD5(img);
                String _realPath = realPath.substring(0, realPath.length()
                        - request.getContextPath().length());
                for (FontFile item : imgFiles)
                {
                    String tempMd5 = FileUtil.getFileMD5(new File(_realPath
                            + item.getPath()));
                    if (md5.equals(tempMd5))
                    {
                        existImgs.add(item);
                    }
                }
            }

            // 将图片信息入库
            FontFile fileBean = new FontFile();
            fileBean.setCompanyId(companyId);
            fileBean.setFileName(fileName);
            fileBean.setFileType(ext);
            fileBean.setPath(contextPath.toString());
            fileBean.setSize(fileSize);
            fileBean.setStatus(Field.Files.IMG);
            fileBean.setCreateTime(new Date());
            receptionContentDao.saveFile(fileBean);

            // 成功将相对路径放入到Content传到action
            messBean.setCode(PageCode.COMMON_SUCCESS);
            fileBean.setList(existImgs);
            messBean.setObjContent(fileBean);
        }
        catch (Exception e)
        {
            throw new PlatException(PageCode.COMMON_ERROR, e.getMessage());
        }

        return messBean;
    }

    /**
     *
     * 前台删除文件
     *
     * @author zhuou
     * @param request
     *            HttpServletRequest
     * @param filesId
     *            文件Id
     * @return MessageBean
     * @throws PlatException
     *             公共异常
     */
    public MessageBean delFile(HttpServletRequest request, long filesId,
            int companyId) throws PlatException
    {
        MessageBean messBean = new MessageBean();

        FontFile fileBean = receptionContentDao.getFileById(companyId, filesId);
        if (null == fileBean)
        {
            messBean.setCode(PageCode.COMMON_SUCCESS);
            messBean.setContent(ResourceManager
                    .getValue(PageCode.DEL_FILE_SUCCESS));
            return messBean;
        }

        String realPath = request.getSession().getServletContext().getRealPath(
                "");
        String _realPath = realPath.substring(0, realPath.length()
                - request.getContextPath().length());
        File file = new File(_realPath + fileBean.getPath());

        // 如果不存在
        if (!file.exists())
        {
            // 删除数据库表数据
            receptionContentDao.delFileByFileId(filesId);

            messBean.setCode(PageCode.COMMON_SUCCESS);
            messBean.setContent(ResourceManager
                    .getValue(PageCode.DEL_FILE_SUCCESS));
            return messBean;
        }

        // 删除文件
        boolean isOk = file.delete();
        if (isOk)
        {
            // 删除数据库表数据
            receptionContentDao.delFileByFileId(filesId);
            messBean.setCode(PageCode.COMMON_SUCCESS);
            messBean.setContent(ResourceManager
                    .getValue(PageCode.DEL_FILE_SUCCESS));
        }
        else
        {
            messBean.setCode(PageCode.DEL_FILE_FAIL);
            messBean.setContent(ResourceManager
                    .getValue(PageCode.DEL_FILE_FAIL));
        }

        return messBean;
    }

    public void setReceptionContentDao(ReceptionContentDao receptionContentDao)
    {
        this.receptionContentDao = receptionContentDao;
    }

    public void setMemberDao(MemberDao memberDao)
    {
        this.memberDao = memberDao;
    }

    public void setWebConfigDao(WebConfigDao webConfigDao)
    {
        this.webConfigDao = webConfigDao;
    }
}
